<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百宝箱 - 个人博客</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style data-page-style="treasure">
        body {
            background-color: #f8fafc;
            color: #1f2937;
            font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

            position: relative;
        }

        /* 背景图片样式，与首页保持一致 */
        .bg-image {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            opacity: 0.9;
            transition: opacity 0.5s ease;
        }

        /* 可调：百宝箱页面整体内容宽度（变小则卡片更窄） */
        .treasure-container {
            max-width: 1200px; /* 可调 */
            margin-top: 28px; /* 与导航栏保持舒适留白 */
        }
        @media (min-width: 992px) {
            .treasure-container { padding-right: 140px; }
        }
        
        /* 页面标题区域 */
        .page-header {
            text-align: center;
            margin-bottom: 40px;
            padding: 40px 0;
            background: linear-gradient(135deg, rgba(102, 178, 255, 0.1), rgba(102, 178, 255, 0.05));
            border-radius: 15px;
            border: 1px solid rgba(102, 178, 255, 0.2);
        }

        .page-header h1 {
            color: #66b2ff;
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 15px;
        }

        .page-header .subtitle {
            color: #8b949e;
            font-size: 1.1rem;
            margin-bottom: 20px;
        }

        .stats-row {
            display: flex;
            justify-content: center;
            gap: 30px;
            flex-wrap: wrap;
        }

        .stat-item {
            text-align: center;
            padding: 10px 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            border: 1px solid rgba(102, 178, 255, 0.1);
        }

        .stat-number {
            font-size: 1.5rem;
            font-weight: bold;
            color: #66b2ff;
        }

        .stat-label {
            font-size: 0.9rem;
            color: #8b949e;
        }

        /* 搜索和筛选区域 */
        .search-filter-section {
            margin-bottom: 24px;
            padding: 16px;
            background: rgba(14, 22, 40, 0.6);
            backdrop-filter: blur(4px);
            border-radius: 12px;
            border: 1px solid rgba(102, 178, 255, 0.18);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25), inset 0 1px rgba(255, 255, 255, 0.04);
        }

        .filter-tabs {
            display: flex;
            justify-content: center;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px; /* 调整分类与下方网格间距 */
        }

        .search-box {
            position: relative;
            max-width: 400px;
            margin: 0 auto 20px;
        }

        .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #8b949e;
            font-size: 16px;
        }

        .search-input {
            width: 100%;
            padding: 12px 45px 12px 15px;
            background: #ffffff;
            border: 1px solid #cbd5e1;
            border-radius: 24px;
            color: #0f172a;
            font-size: 14px;
            transition: all 0.3s ease;
            box-shadow: 0 1px 2px rgba(0,0,0,0.04);
        }

        .search-input::placeholder { color: #94a3b8; }
        .search-icon { color: #94a3b8; }

        .search-input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
            background: #ffffff;
        }

        .filter-tabs {
            display: flex;
            justify-content: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        /* 小方块网格布局 */
        .treasure-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 12px;
        }

        /* 名称缩略，适配小方块 */
        .treasure-name {
            font-size: 12px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
        }

        /* 小方块不显示描述，避免内容撑高 */
        .treasure-description { display: none; }
        .filter-tab {
            padding: 6px 14px;
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 14px;
            color: #334155;
            text-decoration: none;
            font-size: 13px;
            transition: all 0.25s ease;
            cursor: pointer;
        }

        .filter-tab:hover,
        .filter-tab.active {
            background: #f1f5f9;
            border-color: #94a3b8;
            color: #2563eb;
            text-decoration: none;
        }

        .treasure-item {
            background: #ffffff;
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            padding: 10px;
            text-align: center;
            transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            height: 120px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            gap: 6px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.06);
        }

        .treasure-icon-img {
            width: 64px;
            height: 64px;
            object-fit: contain;
            border-radius: 12px;
            padding: 6px;
            border: 1px solid transparent;
            background: conic-gradient(from 180deg at 50% 50%, #60a5fa, #a78bfa, #34d399, #f59e0b, #ef4444, #60a5fa);
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .treasure-icon {
            font-size: 40px;
            background: linear-gradient(135deg, #60a5fa, #a78bfa);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent; /* 渐变填充字体图标 */
        }

        .treasure-name {
            color: #334155;
            font-weight: 600;
            line-height: 1.2;
            margin-top: 2px;
            z-index: 1;
        }

        .treasure-type-badge {
            position: absolute;
            top: 6px;
            left: 6px;
            font-size: 11px;
            padding: 2px 6px;
            border-radius: 8px;
        }

        .treasure-item:hover {
            transform: translateY(-3px);
            border-color: #3b82f6;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        .treasure-item::before {
            content: none; /* 关闭透明扫光效果 */
            background: none;
        }

        .badge-website {
            background: #dcfce7;
            color: #16a34a;
            border: 1px solid #bbf7d0;
        }

        .badge-file {
            background: #ffedd5;
            color: #f97316;
            border: 1px solid #fed7aa;
        }

        .file-size {
            position: absolute;
            bottom: 8px;
            left: 8px;
            font-size: 0.7rem;
            color: #475569;
            background: #f1f5f9;
            padding: 2px 6px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }
    </style>
</head>
<body>
    <div class="bg-image" th:if="${backgroundImage != null and !backgroundImage.isEmpty()}" th:style="|background-image: url(${backgroundImage});|"></div>
    <!-- 导航栏 -->
    <div th:replace="~{fragments/navbar :: navbar}"></div>

    <div class="container treasure-container">
        <!-- 页面标题已移除：根据需求直接展示搜索与分类 -->

        <!-- 搜索和筛选（移除外层框，仅保留搜索栏和分类按钮） -->
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="搜索百宝箱项目...">
            <i class="bi bi-search search-icon"></i>
        </div>
        <div class="filter-tabs">
            <a href="#" class="filter-tab active" data-filter="all">全部</a>
            <a href="#" class="filter-tab" data-filter="website">网站收藏</a>
            <a href="#" class="filter-tab" data-filter="file">文件</a>
        </div>

        <!-- 宝箱网格 -->
        <div class="treasure-grid" id="treasureGrid">
            <!-- 所有项目 -->
            <div th:each="item : ${allItems}" 
                 class="treasure-item" 
                 th:data-type="${item.type.name().toLowerCase()}"
                 th:data-name="${item.displayName}"
                 th:data-url="${item.url}"
                 th:data-file="${item.filePath}"
                 th:data-filename="${item.originalFileName}"
                 th:data-mime="${item.mimeType}"
                 th:data-id="${item.id}">
                <!-- 类型标识已移除 -->
                <span class="treasure-type-badge"
                      th:classappend="${item.type.name() == 'WEBSITE'} ? 'badge-website' : 'badge-file'"
                      th:text="${item.type.description}" th:remove="all"></span>
                
                <!-- 图标 -->
                <img class="treasure-icon-img"
                     th:if="${item.icon != null and (#strings.contains(item.icon,'://') or #strings.startsWith(item.icon,'/'))}"
                     th:src="${item.icon}" alt="图标">
                <i class="treasure-icon bi"
                   th:if="${item.icon == null or (!#strings.contains(item.icon,'://') and !#strings.startsWith(item.icon,'/'))}"
                   th:classappend="${item.icon != null ? item.icon : 'bi-globe'}"></i>
                
                <!-- 名称 -->
                <div class="treasure-name" th:text="${item.displayName}">项目名称</div>
                
                <!-- 描述 -->
                <div class="treasure-description" th:text="${item.description}" th:if="${item.description != null and !item.description.isEmpty()}">项目描述</div>
                
                <!-- 文件大小（仅文件类型显示） -->
                <div class="file-size" th:if="${item.type.name() == 'FILE' and item.fileSize != null}" th:text="${item.getFormattedFileSize()}">文件大小</div>
            </div>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" id="emptyState" style="display: none;">
            <i class="bi bi-inbox"></i>
            <h3>暂无内容</h3>
            <p>还没有添加任何项目到百宝箱</p>
        </div>

        <!-- 搜索无结果 -->
        <div class="empty-state" id="noResults" style="display: none;">
            <i class="bi bi-search"></i>
            <h3>未找到匹配项目</h3>
            <p>尝试使用其他关键词搜索</p>
        </div>
    </div>

    <!-- 管理按钮（仅管理员可见） -->
    <div class="admin-actions" sec:authorize="hasRole('ADMIN')">
        <a href="/admin/treasure" class="admin-btn">
            <i class="bi bi-gear"></i>
            管理百宝箱
        </a>
    </div>

    <!-- 文件预览模态框 -->
    <div class="modal fade" id="filePreviewModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-fullscreen">
        <div class="modal-content bg-white text-dark border-0 rounded-0">
          <div class="modal-header border-0 p-2">
            <h5 class="modal-title" id="filePreviewTitle">文件预览</h5>
            <div class="d-flex align-items-center gap-2 ms-auto">
              <a id="fileDownloadBtn" class="btn btn-sm btn-primary" href="#" target="_blank" download><i class="bi bi-download me-1"></i>下载</a>
              <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
          </div>
          <div class="modal-body p-0" style="height:100vh">
              <iframe id="filePreviewFrame" style="width:100%; height:100vh; border:0;" frameborder="0"></iframe>
              <div id="filePreviewUnsupported" class="text-center text-muted" style="display:none; padding:20px;">
                  此类型暂不支持在线预览，请点击下载。
              </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 搜索功能
        const searchInput = document.getElementById('searchInput');
        const treasureGrid = document.getElementById('treasureGrid');
        const emptyState = document.getElementById('emptyState');
        const noResults = document.getElementById('noResults');
        const filterTabs = document.querySelectorAll('.filter-tab');
        
        let currentFilter = 'all';
        let allItems = [];
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            allItems = Array.from(document.querySelectorAll('.treasure-item'));
            // 绑定点击事件（网站打开、文件预览）
            allItems.forEach(function(item) {
                item.addEventListener('click', function() {
                    const type = item.dataset.type;
                    if (type === 'website') {
                        const url = item.dataset.url;
                        if (url) window.open(url, '_blank');
                    } else {
                        const file = item.dataset.file;
                        const name = item.dataset.filename;
                        const mime = item.dataset.mime;
                        const id = item.dataset.id;
                        previewFileById(id, file, name, mime);
                    }
                });
                item.dataset.boundClick = '1';
            });
            checkEmptyState();

            const previewModalEl = document.getElementById('filePreviewModal');
            if (previewModalEl) {
                previewModalEl.addEventListener('hidden.bs.modal', function(){
                    const frame = document.getElementById('filePreviewFrame');
                    if (frame) frame.src = '';
                });
            }
        });
        
        // 搜索功能
        searchInput.addEventListener('input', function() {
            const keyword = this.value.toLowerCase().trim();
            filterItems(keyword, currentFilter);
        });
        
        // 筛选功能
        filterTabs.forEach(tab => {
            tab.addEventListener('click', function(e) {
                e.preventDefault();
                
                // 更新活动标签
                filterTabs.forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                
                currentFilter = this.dataset.filter;
                const keyword = searchInput.value.toLowerCase().trim();
                filterItems(keyword, currentFilter);
            });
        });
        
        // 筛选项目
        function filterItems(keyword, filter) {
            let visibleCount = 0;
            
            allItems.forEach(item => {
                const name = item.dataset.name.toLowerCase();
                const type = item.dataset.type;
                
                const matchesKeyword = !keyword || name.includes(keyword);
                const matchesFilter = filter === 'all' || type === filter;
                
                if (matchesKeyword && matchesFilter) {
                    item.style.display = 'flex';
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            });
            
            // 显示相应的空状态
            if (visibleCount === 0) {
                treasureGrid.style.display = 'none';
                emptyState.style.display = 'none';
                noResults.style.display = keyword ? 'block' : 'none';
                if (!keyword && allItems.length === 0) {
                    emptyState.style.display = 'block';
                }
            } else {
                treasureGrid.style.display = 'grid';
                emptyState.style.display = 'none';
                noResults.style.display = 'none';
            }
        }
        
        // 检查空状态
        function checkEmptyState() {
            if (allItems.length === 0) {
                treasureGrid.style.display = 'none';
                emptyState.style.display = 'block';
            }
        }
        
        // 文件下载功能
        function downloadFile(filePath, fileName) {
            // 创建一个临时链接进行下载
            const link = document.createElement('a');
            link.href = filePath;
            link.download = fileName || '下载文件';
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 添加键盘快捷键支持
        document.addEventListener('keydown', function(e) {
            // Ctrl/Cmd + K 聚焦搜索框
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                searchInput.focus();
            }
            
            // ESC 清空搜索
            if (e.key === 'Escape' && document.activeElement === searchInput) {
                searchInput.value = '';
                filterItems('', currentFilter);
            }
        });
        
        // 添加搜索框聚焦提示
        searchInput.addEventListener('focus', function() {
            this.placeholder = '输入关键词搜索... (ESC 清空)';
        });
        
        searchInput.addEventListener('blur', function() {
            this.placeholder = '搜索百宝箱项目...';
        });
    function previewFileById(id, filePath, fileName, mime){
        if (!id) return;
        const ext = (fileName || '').split('.').pop().toLowerCase();
        const isImage = (mime && mime.startsWith('image/')) || ['jpg','jpeg','png','gif','bmp','webp','svg'].includes(ext);
        const isPdf = (mime && mime.toLowerCase().includes('pdf')) || ext === 'pdf';
        const previewUrl = '/treasure/preview/' + id;
        const downloadUrl = '/treasure/download/' + id;
    
        const modalEl = document.getElementById('filePreviewModal');
        const frame = document.getElementById('filePreviewFrame');
        const unsupported = document.getElementById('filePreviewUnsupported');
        const titleEl = document.getElementById('filePreviewTitle');
        const downloadBtn = document.getElementById('fileDownloadBtn');
    
        if (!modalEl || !frame) { window.open(downloadUrl, '_blank'); return; }
    
        titleEl.textContent = fileName || '文件预览';
        downloadBtn.href = downloadUrl;
        downloadBtn.download = fileName || '下载文件';
    
        if (isImage || isPdf) {
            unsupported.style.display = 'none';
            frame.src = previewUrl;
        } else {
            frame.src = '';
            unsupported.style.display = 'block';
        }
    
        const modal = new bootstrap.Modal(modalEl, { keyboard: true });
        modal.show();
    }
    
    </script>
</body>
</html>